package timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingDeque;

/**
 * @author Created by chenxin34 on 2018/3/23 上午9:53.
 */
public class TimerTest {
    public static void main(String[] args) {
        //long running task delay short task
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("long task");
                throw new RuntimeException();
//                try {
//                    Thread.sleep(10000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }, 0, 10000);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("short task");
            }
        }, 1000, 1000);
    }

    boolean newTasksMayBeScheduled = true;

    BlockingDeque queue;
    long currentTime, executionTime;

    /**
     *
    private void mainLoop() {
        //循环
        while (true) {
            synchronized(queue) {
                while (queue.isEmpty() && newTasksMayBeScheduled)
                    queue.wait();
                task = queue.getMin();
                synchronized(task.lock) {
                    if (task.state == TimerTask.CANCELLED) {
                        queue.removeMin();continue;
                    }
                    //判断任务执行时间是否到期
                    if (taskFired = (executionTime<=currentTime)) {
                        if (task.period == 0) { // Non-repeating, remove
                            queue.removeMin();
                            task.state = TimerTask.EXECUTED;
                        } else { // Repeating task, reschedule
                            queue.rescheduleMin();
                        }
                    }
                }
                if (!taskFired) // Task hasn't yet fired; wait
                    queue.wait(executionTime - currentTime);
            }
            if (taskFired)  // Task fired; run it, holding no locks
                task.run();
        }
    }

     **/
}
